//
//  VoiceRecord2ViewControlller.m
//  FMRecordVideo
//
//  Created by 高波 on 2019/5/5.
//  Copyright © 2019 SF. All rights reserved.
//

#define klastRecordPath @"lastRecordPath"

#import "VoiceRecord2ViewControlller.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import "MyRecorder.h"
#import "SoundTool.h"
#import "lame.h"
@interface VoiceRecord2ViewControlller ()
{
    BOOL _isHasRecordFile; // 标记是否有录音文件
    NSString *_mp3Url; // 记录录音文件url
    NSString *_mp3Time; // 录音时间
    
    
    NSTimeInterval _start;
    NSTimeInterval _end;
    NSTimer *_timer;
}

@property (weak, nonatomic) IBOutlet UILabel *timeLeft;
@property (weak, nonatomic) IBOutlet UILabel *time;

@property (weak, nonatomic) IBOutlet UIProgressView *progress;


@property (weak, nonatomic) IBOutlet UIView *operateView;
@property (weak, nonatomic) IBOutlet UIButton *startButton;
@property (weak, nonatomic) IBOutlet UIButton *stopButton;


@property (weak, nonatomic) IBOutlet UIButton *cancelButton;
@property (weak, nonatomic) IBOutlet UIButton *refreshButton;
@property (weak, nonatomic) IBOutlet UIButton *sureButton;

@end

@implementation VoiceRecord2ViewControlller

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [UIColor clearColor];
    [self adjustUI];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.view.backgroundColor = [UIColor clearColor];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.view.backgroundColor = [UIColor clearColor];
}


- (void)adjustUI
{
    self.progress.progress = 0.0;
    
    self.operateView.layer.cornerRadius = 29.0f;
    self.operateView.clipsToBounds = YES;
    self.operateView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.operateView.layer.borderWidth = 5.0f;
    
    self.startButton.layer.cornerRadius = 21.5f;
    self.startButton.clipsToBounds = YES;
    self.startButton.hidden = NO;
    
    self.stopButton.layer.cornerRadius = 5.0f;
    self.stopButton.clipsToBounds = YES;
    self.stopButton.hidden = YES;
}


- (IBAction)start:(id)sender
{
    self.startButton.hidden = YES;
    self.stopButton.hidden = NO;
    
//    self.refreshButton.enabled = NO;
//    self.sureButton.enabled = NO;
    
    _isHasRecordFile = YES;
    _start = [[NSDate date] timeIntervalSince1970];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timeCount) userInfo:nil repeats:YES];
    [self record];
}

- (void)timeCount
{
    _end = [[NSDate date] timeIntervalSince1970];
    NSInteger recordTime = (NSInteger)(_end - _start);
    if (recordTime >= 60) {
        recordTime = 60;
    }
    self.time.text = [self convertTimeWithTimeCount:recordTime];
    self.timeLeft.text = [self convertLeftTimeWithTimeCount:recordTime];
    
    CGFloat progress = (CGFloat)recordTime / 60;
    [self.progress setProgress:progress animated:YES];
    
    if (recordTime >= 60) {
        [self stop:nil];
    }
    NSLog(@"recordTime:%f",_end - _start);
}

- (NSString *)convertTimeWithTimeCount:(NSInteger)time
{
    if (time <= 9) {
        return [NSString stringWithFormat:@"0:0%ld",(long)time];
    }else if (time <= 59) {
        return [NSString stringWithFormat:@"0:%ld",(long)time];
    }else{
        NSInteger f = time / 60;
        NSInteger m = time % 60;
        if (f <= 9) {
            if (m <= 9) {
                return [NSString stringWithFormat:@"%ld:0%ld",(long)f,(long)m];
            }else {
                return [NSString stringWithFormat:@"%ld:%ld",(long)f,(long)m];
            }
        }else {
            if (m <= 9) {
                return [NSString stringWithFormat:@"%ld:0%ld",(long)f,(long)m];
            }else {
                return [NSString stringWithFormat:@"%ld:%ld",(long)f,(long)m];
            }
        }
    }
}

- (NSString *)convertLeftTimeWithTimeCount:(NSInteger)time
{
    if (time <= 9) {
        return [NSString stringWithFormat:@"0:0%ld",(long)time];
    }else if (time <= 59) {
        return [NSString stringWithFormat:@"0:%ld",(long)time];
    }else{
        NSInteger f = time / 60;
        NSInteger m = time % 60;
        if (f <= 9) {
            if (m <= 9) {
                return [NSString stringWithFormat:@"%ld:0%ld",(long)f,(long)m];
            }else {
                return [NSString stringWithFormat:@"%ld:%ld",(long)f,(long)m];
            }
        }else {
            if (m <= 9) {
                return [NSString stringWithFormat:@"%ld:0%ld",(long)f,(long)m];
            }else {
                return [NSString stringWithFormat:@"%ld:%ld",(long)f,(long)m];
            }
        }
    }
}

- (void)dealloc
{
    [_timer invalidate];
    _timer = nil;
}

- (void)record
{
    BOOL isCanRecord = [self canRecord];
    if (isCanRecord) {
        MyRecorder *recorder = [MyRecorder sharedMyRecorder];
        if ([recorder isRecording]) {
            [[MyRecorder sharedMyRecorder] stopRecording];
        } else {
            [[MyRecorder sharedMyRecorder] startRecording];
        }
    }
}

- (BOOL)canRecord
{
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                if (granted) {
                    bCanRecord = YES;
                } else {
                    bCanRecord = NO;
                }
            }];
        }
    }
    return bCanRecord;
}

- (IBAction)stop:(id)sender
{
    self.startButton.hidden = NO;
    self.stopButton.hidden = YES;
    
//    self.refreshButton.enabled = YES;
//    self.sureButton.enabled = YES;
    
    [_timer invalidate];
    
    MyRecorder *recorder = [MyRecorder sharedMyRecorder];
    if ([recorder isRecording]) {
        [[MyRecorder sharedMyRecorder] stopRecording];
        [self audio_PCMtoMP3];
    }
}



- (IBAction)cancel:(id)sender
{
    [self stop:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)refresh:(id)sender
{
//    self.refreshButton.enabled = NO;
//    self.sureButton.enabled = NO;
    
    [self stop:nil];
    
    self.progress.progress = 0.0;
    self.timeLeft.text = @"0:00";
    self.time.text = @"0:00";
    
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:klastRecordPath];
    
}

- (IBAction)sure:(id)sender
{
    [self stop:nil];
    
    NSString *path = [[NSUserDefaults standardUserDefaults] objectForKey:klastRecordPath];
    if (path) {
        path = [path stringByReplacingOccurrencesOfString:@"caf" withString:@"mp3"];
        NSURL *mp3Url = [NSURL fileURLWithPath:path];
        
        [self dismissViewControllerAnimated:YES completion:^{
            if ([self.delegate respondsToSelector:@selector(VoiceRecord2ViewControlllerDismissWithUrl:)]) {
                [self.delegate VoiceRecord2ViewControlllerDismissWithUrl:mp3Url];
            }
        }];
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)audio_PCMtoMP3
{
    NSString *lastRecordAddress = [[NSUserDefaults standardUserDefaults] objectForKey:klastRecordPath];
    NSString *mp3Address = [lastRecordAddress stringByReplacingOccurrencesOfString:@"caf" withString:@"mp3"];
    NSString *mp3FileName = mp3Address;
    mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];
    NSString *mp3FilePath = mp3Address;
    
    @try {
        int read, write;
        
        FILE *pcm = fopen([lastRecordAddress cStringUsingEncoding:1], "rb");  //source 被转换的音频文件位置
        fseek(pcm, 4*1024, SEEK_CUR);                                //skip file header
        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output 输出生成的Mp3文件位置
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, 44100);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
    }
    @finally {
        NSLog(@"MP3生成成功: %@",mp3Address);
    }
}

@end
